package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 两个线程交换数据？为啥要交换
 * Created by gavin on 15-9-2.
 */
public class ExechangerTest {
    public static void main(String[] args)
    {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Exchanger<String> exchanger = new Exchanger<String>();
        executorService.execute(new ExchangeRun(exchanger));
        executorService.execute(new ExchangeRun(exchanger));
    }
}

class ExchangeRun implements Runnable{
    private Exchanger<String> exchanger;

    public void run() {
        System.out.println(Thread.currentThread().getName()+"  start");
        try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String data = "data<"+Thread.currentThread().getName()+">";

        try {
            data = exchanger.exchange(data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"  "+data);
    }

    public ExchangeRun(Exchanger<String> exchanger) {
        this.exchanger = exchanger;
    }
}
